package com.leyou.user.interceptor;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constant.LyConstants;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 注意，当前拦截器校验的并非是页面请求的登录权限，而是其他服务的访问权限，如果没有权限，直接阻止访问。
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProp;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取到当前请求的请求头
        String token = request.getHeader(LyConstants.APP_TOKEN_HEADER);
        //如果来访服务没有携带token，直接阻止访问
        if(StringUtils.isEmpty(token)){
            log.error("【来访服务token为空，终止访问！】");
            //阻止继续访问
            return false;
        }
        //解析token
        Payload<AppInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), AppInfo.class);
        }catch (Exception e){
            log.error("【来访服务token不合法，终止访问！】");
            return false;
        }
        //获取来访服务具有的权限列表
        List<Long> targetList = payload.getUserInfo().getTargetList();
        //判断来访服务是否有访问当前服务的权限
        if(!targetList.contains(jwtProp.getApp().getId())){
            log.error("【来访服务没有访问{}的权限，终止访问！】", jwtProp.getApp().getServiceName());
            return false;
        }
        log.info("【来访服务顺利通过服务间的权限校验！】");
        return true;
    }

}
